<template>
  <div class="filelist-container">
    <!-- 上传、新建、删除和搜索按钮 -->
    <!-- <el-row
      :gutter="24"
      type="flex"
      justify="end"
      style="margin-left: 0px"
    >
      <el-input
        v-model="searchValue"
        clearable
        placeholder="搜索文件名"
        size="small"
        style="width: 240px; margin-right: 10px"
        @keypress.native.enter="handSearch"
        @clear="handClearSearch"
      >
        <el-button
          slot="append"
          size="small"
          icon="el-icon-search"
          @click="handSearch"
        ></el-button>
      </el-input>
    </el-row> -->

    <div class="file-path">
      <!-- 显示文件层级路径 -->
      <el-row
        type="flex"
        align=""
      >
        <span class="path-name">全部文件</span>
      </el-row>
    </div>

    <!-- 文件列表显示 -->
    <div class="file-table">
      <el-table
        v-loading="listLoading"
        :data="dataSource"
        :border="false"
        @selection-change="handleSelectionChange"
        @cell-mouse-enter="handleRowMouseMove"
        @cell-mouse-leave="rowSelectedIndex = null"
        style="width: 100%"
      >
        <el-table-column
          type="selection"
          width="42"
        ></el-table-column>
        <el-table-column
          label="名称"
          prop="name"
          min-width="200"
        >
          <template slot-scope="{ row }">
            <image-type
              :width="32"
              :fileType="row.type"
            >
              <span
                style="
                  display: inline-block;
                  vertical-align: sub;
                  margin-right: 6px;
                "
                @click="handChangeTreePath(row)"
              >{{ row.title || row.filename }}</span>
            </image-type>
          </template>
        </el-table-column>
        <el-table-column width="120">
          <template slot-scope="{ row }">
            <div v-if="row.id === rowSelectedIndex">
              <el-button
                type="text"
                size="small"
                icon="el-icon-delete"
                style="padding: 0;visibility: hidden;"
              >删除</el-button>
              <el-button
                type="text"
                size="small"
                icon="el-icon-download"
                style="padding: 0"
                :disabled="!!row.title"
                @click="downloadFile(row)"
              >下载</el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="创建者"
          prop="username"
          width="150"
        />
        <el-table-column
          label="创建时间"
          prop="create_time"
          width="150"
        >
          <template slot-scope="{ row }">{{
            parseTime(row.create_time, "{y}/{m}/{d} {h}:{i}")
          }}</template>
        </el-table-column>
        <el-table-column
          label="大小"
          align="left"
          prop="size"
          width="120"
        >
          <template
            slot-scope="{ row }"
            v-if="row.id > 0"
          >{{
            row.size | formatFileSize
          }}</template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        class="pageWrapper"
        v-show="total > 0"
        :total="total"
        :layout="'total, prev, pager, next'"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.size"
        @pagination="handlePage"
      />
    </div>
  </div>
</template>
  <script>
import { getFileType, parseTime, uuid } from "@/utils/index.js";
import { delHasFile } from "@/api/work.js";
import {
  queryFileCatalogList,
  queryTaskCenterFileList,
  createFileCatalog,
  deleteFileCatalog,
  updateFileCatalog,
  deleteTaskCenterFile,
  updateTaskCenterFile,
  queryShareFileList,
  postAppointShare
} from "@/api/document";

export default {
  name: "FileList",
  props: {
    preview: {
      type: Boolean,
      default: false
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    preFileList: {
      type: Array
    }
  },
  components: {
    ImageType: () => import("@/components/ImageType"),
    Pagination: () => import("@/components/Pagination"),
    FileUpload: () => import("@/components/FileUpload"),
    UserManager: () =>
      import("@/views/markSys/taskCenter/components/userManager")
  },
  data() {
    return {
      treePath: [],
      dataSource: [], // 文件列表
      multipleSelection: [],
      listQuery: {
        page: 1,
        size: 10,
        is_msg: 1
      },
      fileTypeValue: "",
      fileTypeOption: [
        { name: "图片", value: "image" },
        { name: "Word", value: "word" },
        { name: "Excel", value: "excel" },
        { name: "PPT", value: "ppt" },
        { name: "PDF", value: "pdf" },
        { name: "文本", value: "txt" },
        { name: "音频", value: "audio" },
        { name: "视频", value: "vadio" }
      ],
      listLoading: false,
      total: 0,
      dialogUpperVisible: false,
      dialogUploadVisible: false,
      dialogShareVisible: false,
      catalogName: "", // 新建文件夹名称
      searchValue: "", // 搜索值
      rowSelectedIndex: null, // 鼠标移入行index
      uploadParam: null, // 上传文件参数
      modalType: "新建文件夹"
    };
  },
  mounted() {
    this.requestFileCatalogList();
  },
  methods: {
    parseTime,
    /**
     * 输入关键字搜索文件
     */
    async handSearch() {
      this.listQuery.page = 1;
      this.fetchSeach();
    },
    async fetchSeach() {
      this.listLoading = true;
      const { data: fileList } = await queryTaskCenterFileList({
        search: this.searchValue,
        ...this.listQuery
      });

      const { count, results } = fileList;

      this.dataSource = results;
      this.total = count;
      this.listLoading = false;
    },
    /**
     * 清空搜索条件
     */
    handClearSearch() {
      this.searchValue = null;
      this.listQuery.page = 1;
      this.requestFileCatalogList();
    },
    /**
     * 分页搜索
     */
    handlePage(val) {
      this.listQuery.page = val.page;
        this.requestFileCatalogList();
      
    },

    /**
     * 点击文件夹时进入此目录，更新数据
     * 如果是文件则预览
     */
    handChangeTreePath(item) {
      if (item.title) {
        this.listQuery.page = 1;
        this.treePath.push(item);
      } else {
        this.previewFile(item);
      }
    },
    // 跳转到在线office页面
    previewFile(row) {
      const { id, type, url } = row;
      const canPreviewOnlyOffice = [
        "doc",
        "docx",
        "wps",
        "pdf",
        "xls",
        "xlsx",
        "pptx"
      ];
      if (
        [
          "bmp",
          "png",
          "gif",
          "jpeg",
          "jpg",
          "mp4",
          "mp3",
          "json",
          "txt",
          "js"
        ].includes(type)
      ) {
        window.open(url, "_blank");
        return;
      } else if (canPreviewOnlyOffice.includes(type)) {
        const { href } = this.$router.resolve({
          name: "FilePreview",
          query: {
            previewType: 0,
            fileId: id
          }
        });
        window.open(href, "_blank");
      } else {
        this.$message.info(`所选文件暂不支持在线预览`);
      }
    },

    /**
     * 选中行列表
     */
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    /**
     * 设置鼠标移入行index
     */
    handleRowMouseMove(row) {
      if (!row.id) return;
      this.rowSelectedIndex = row.id;
    },
    /**
     * 创建a标签下载文件
     */
    downloadFile(row) {
      const { url, filename } = row;
      let a = document.createElement("a");
      a.download = filename;
      a.href = url;
      a.click();
      window.URL.revokeObjectURL(url);
    },
    /**
     * 获取选中文件后对话框标题提示
     */
    getDeleteTootipTitle() {
      if (!this.multipleSelection.length) {
        return "";
      }
      const { title, filename } = this.multipleSelection[0];
      const length = this.multipleSelection.length;
      let name = title || filename;
      if (name.length > 20) {
        let subStr1 = name.substr(0, 10);
        let subStr2 = name.substr(name.length - 8, 8);
        name = subStr1 + "..." + subStr2;
      }
      if (length > 1) {
        return name + "等" + length + "项";
      }
      return name;
    },
    /**
     * 显示删除文件或目录对话框
     */
    showDeleteConfirm() {
      this.$confirm(
        "将所选文件移除公告通知, 是否继续?",
        `提示 - ${this.getDeleteTootipTitle()}`,
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).then(() => {
        this.handDeleteFileOrCatalog();
      });
    },
    /**
     * 发送删除文件或目录请求，成功后刷新列表
     */
    async handDeleteFileOrCatalog() {
      const hide = this.$message("正在配置");
      const list = this.multipleSelection;
      if (list.length === this.dataSource.length) {
        this.listQuery.page = 1;
      }
      const reqList = list.map(item => {
        return new Promise(async (resolve, rejct) => {
          const { id, title, filename } = item;
          const result = await updateTaskCenterFile(id, { is_msg: 0 });
          if (result) {
            resolve(result);
          }
        });
      });
      Promise.all(reqList).then(res => {
        hide.close();
        this.$message.success("从信息快报移除操作成功！");
        this.multipleSelection = [];
          this.requestFileCatalogList();
        
      });
    },
    /**
     * 根据目录ID请求列表
     */
    async requestFileCatalogList() {
      this.listLoading = true;
      const { parent, page } = this.listQuery;
      let result = null;

      const { data: fileCatalog } = await queryTaskCenterFileList({
        ...this.listQuery
      });
      const { count, results } = fileCatalog;

      this.dataSource = results;
      this.total = count;
      this.listLoading = false;
    }
  }
};
</script>
  <style lang="scss">
.filelist-container {
  padding: 20px;
  .file-path {
    margin: 12px 11px 4px;
    .path-name {
      font-size: 14px;
    }
    .path-active {
      color: #409eff;
    }
  }
  .el-alert.is-light .el-alert__closebtn {
    color: #409eff;
    line-height: 20px;
  }
  .el-dialog__footer {
    margin-top: -20px;
  }
  // .el-table__body {

  // .el-checkbox {

  //   margin-left: 12px !important;
  // }
  // .is-checked {
  //   margin-left: 7px !important;
  // }
  // }
}
</style>